package com.wmd.endpoint;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wmd.core.exceptions.GenericResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Simple to Introduction
 *
 * @projectName:scs-platform
 * @packageName:com.wmd.iot.badge.endpoint
 * @className:WebSocketServer
 * @Description:[推送围栏进出警告websocket]
 * @Author:luyincheng
 * @CreateDate:2021/1/7 10:24
 * @blog:[方法具体上行/下行参数文档]
 */
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    public static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //发送消息
    public void sendMessageFormatData(Session session, Object message,String type) throws IOException {
        if (session != null) {
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(FormatData(message,type));
            }
        }
    }
    public static String FormatData(Object message,String type){
        JSONObject data=new JSONObject();
        data.put("type",type);
        data.put("data",message);
        return data.toJSONString();
    }
    //给指定用户发送信息
    public void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //给所有用户发消息
    public void sendMessageAll(String message) {
        sessionPools.forEach((k, v) -> {
            try {
                sendMessage(v, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    public void sendMessageFormatDataAll(Object message,String type) {
        String data=FormatData(message,type);
        sessionPools.forEach((k, v) -> {
            try {
                sendMessage(v, data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
        sessionPools.put(session.getId(), session);
        addOnlineCount();
        try {

            sendMessage(session, JSON.toJSONString(new GenericResponse(200, "success", null)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName, Session session) {
        sessionPools.remove(session.getId());
        subOnlineCount();
        log.info(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        message = "客户端：" + message + ",已收到";
        System.out.println(message);

        sendMessage(session, "收到");
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}
